const { join, dirname } = require('node:path')
const { writeFileSync, existsSync } = require('node:fs')

const { log } = require('./logger.js')

// We don't have a specific entry for the augmenting file in `package.json > exports`
// We rely on the wildcard entry, so we use a deep import, instead of let's say `quasar/feature-flags`
// When using TypeScript `moduleResolution: "bundler"`, it requires the file extension.
// This may sound unusual, but that's because it seems to treat wildcard entries differently.
//
// Keep in sync with `create-quasar/templates/**/store-flag.d.ts`
const template = `/* eslint-disable */
/*
  WARNING: DO NOT MODIFY OR DELETE
  This file is auto-generated by Quasar CLI
  It's recommended to NOT .gitignore it
  You don't have to use TypeScript in your project, don't worry
*/
import "quasar/dist/types/feature-flag.d.ts";

declare module "quasar/dist/types/feature-flag.d.ts" {
  interface QuasarFeatureFlags {
    __FEATURE_NAME__: true;
  }
}
`

module.exports.generateTypesFeatureFlag = function generateTypesFeatureFlag (modeName, appPaths) {
  const destFlagPath = appPaths.resolve[ modeName ](`${ modeName }-flag.d.ts`)

  writeFileSync(
    destFlagPath,
    template.replace('__FEATURE_NAME__', modeName)
  )
}

module.exports.ensureTypesFeatureFlags = function ensureTypesFeatureFlags (quasarConf) {
  // Flags must be available even in pure JS codebases,
  //    because boot and configure wrappers functions files will
  //    provide autocomplete based on them also to JS users
  // Flags files should be copied over, for every enabled mode,
  //    every time `quasar dev` and `quasar build` are run:
  //    this automatize the upgrade for existing codebases
  const { appPaths, mode } = quasarConf.ctx

  if (quasarConf.metaConf.hasStore === true) {
    const destFlagPath = appPaths.resolve.app(
      join(dirname(quasarConf.sourceFiles.store), 'store-flag.d.ts')
    )

    if (!existsSync(destFlagPath)) {
      writeFileSync(
        destFlagPath,
        template.replace('__FEATURE_NAME__', 'store')
      )
      log('"store" feature flag was missing and has been regenerated')
    }
  }

  for (const modeName of Object.keys(mode)) {
    if (modeName === 'spa' || mode[ modeName ] !== true) {
      continue
    }

    const destFlagPath = appPaths.resolve[ modeName ](`${ modeName }-flag.d.ts`)

    if (!existsSync(destFlagPath)) {
      writeFileSync(
        destFlagPath,
        template.replace('__FEATURE_NAME__', modeName)
      )
      log(`"${ modeName }" feature flag was missing and has been regenerated`)
    }
  }
}
